﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Windvoice.Blog;
using Windvoice.Authorize;

namespace Windvoice.Controllers.Page
{
    public class BlogController : Windvoice.Framework.ControllerBase
    {
        //
        // GET: /Blog/
        public ActionResult Index(string key, int? page)
        {
            int CategoryID = 0;
            if (!String.IsNullOrEmpty(key))
            {
                var category = Windvoice.Blog.Category.Get(key);
                if (category == null)
                    return View("_404");

                CategoryID = category.ID;
                ViewBag.Category = category;
            }

            int PageIndex = page == null ? 1 : page.Value;
            int PageSize = 24, RecordCount = 0;

            ViewBag.Blogs = Article.GetList(PageIndex, PageSize, CategoryID, out RecordCount);
            ViewBag.PageSize = PageSize;
            ViewBag.RecordCount = RecordCount;

            return View();
        }

        public ActionResult Detail(string key)
        {
            var article = Article.Get(key);
            if (article == null)
                return View("_404");

            Article.HitPlus(article.ID);

            ViewBag.RelatedBlogs = Article.Search(article.Title);
            ViewBag.Neighbours = article.GetNeighbours();
            ViewBag.Comments = Comment.GetList(article.ID);
            return View(article);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Detail(string key, FormCollection formValues)
        {
            if (Session["user"] != null)
            {
                string Content = formValues["comment"];
                var article = Article.Get(key);

                Comment comment = new Comment()
                {
                    ArticleID = article.ID,
                    Content = Content,
                    CreateTime = DateTime.Now,
                    IP = Request.UserHostAddress,
                    UserID = ((User)Session["user"]).ID
                };
                comment.Save();
            }

            return Redirect("/blog/" + key);
        }
    }
}
